package com.demo.service;

import com.demo.annotation.CacheExpire;
import com.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class UserService {

    @Resource
    private DbShardingStrategyService dbShardingStrategyService;

    public void saveUser() {
        dbShardingStrategyService.insertAfterPublisher(System.currentTimeMillis());
        log.info("saveUser");
    }

    @Cacheable(cacheNames = "user:getUser:", key = "#userId")
    @CacheExpire(60)
    public List<User> getUser(Long userId) {
        return dbShardingStrategyService.selectByUserId(userId);
    }

    @Cacheable(cacheNames = "user:getUser:userId:", key = "#userId")
    @CacheExpire(30)
    public List<User> getUserByUserId(Long userId) {
        return dbShardingStrategyService.selectByUserId(userId);
    }

    /**
     * 返回null不缓存
     * @param userId
     * @return
     */
    @Cacheable(cacheNames = "user:returnNull:", key = "#userId", unless = "#result == null")
    public List<User> returnNull(Long userId) {
        log.info("用户id：{}", userId);
        return null;
    }

    /**
     * 删除缓存
     * @param userId
     */
    @CacheEvict(cacheNames = "user:getUser:", key = "#userId")
    public void deleteCache(Long userId) {

    }
}
